#include "temperaturechart.h"
#include <QDebug>
#include <algorithm>

TemperatureChart::TemperatureChart(QWidget *parent) : QWidget(parent)
{
    // 设置背景透明
    setAttribute(Qt::WA_TranslucentBackground);
}

void TemperatureChart::setTemperatureData(const QList<Forecast> &forecastList)
{
    // 清空原有数据
    highTemps.clear();
    lowTemps.clear();
    dates.clear();

    // 检查输入数据
    if(forecastList.isEmpty()) {
        qDebug() << "警告：温度数据为空，使用默认值";
        // 添加一些默认数据避免绘图出错
        for(int i=0; i<7; ++i) {
            highTemps << 25.0;
            lowTemps << 20.0;
            dates << QString("周%1").arg(i+1);
        }
        update();
        return;
    }

    // 处理每项数据
    for(const Forecast &forecast : forecastList) {
        // 安全提取温度值
        double high = extractTemperature(forecast.high);
        double low = extractTemperature(forecast.low);
        
        // 检查温度值合理性
        if(high < -50 || high > 50 || low < -50 || low > 50) {
            qDebug() << "无效温度值，使用默认值";
            high = 25.0;
            low = 20.0;
        }

        highTemps.append(high);
        lowTemps.append(low);
        dates.append(forecast.week);
    }

    update();
}

void TemperatureChart::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    
    if (highTemps.isEmpty() || lowTemps.isEmpty()) {
        return;
    }
    
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true); // 抗锯齿
    
    // 绘制温度曲线和填充区域
    drawFillArea(painter);
    drawTemperatureCurve(painter);
    
    // 绘制坐标轴
    drawAxes(painter);
    
    // 绘制温度标签
    drawTemperatureLabels(painter);
}

void TemperatureChart::calculateYRange(double &min, double &max) const
{
    if (highTemps.isEmpty() || lowTemps.isEmpty()) {
        min = 0;
        max = 40;
        return;
    }
    
    // 找到最高温和最低温
    min = *std::min_element(lowTemps.begin(), lowTemps.end());
    max = *std::max_element(highTemps.begin(), highTemps.end());
    
    // 使用qFloor和qCeil代替std::floor和std::ceil
    min = qFloor(min) - 2;
    max = qCeil(max) + 2;
    
    // 确保最小值不低于0
    min = qMax(min, 0.0);
}

void TemperatureChart::drawAxes(QPainter &painter)
{
    int width = this->width();
    int height = this->height();
    int padding = 40; // 内边距
    
    // 设置画笔
    QPen pen(Qt::black);
    pen.setWidth(2);
    painter.setPen(pen);
    
    // 绘制横坐标轴（只画线，不画刻度）
    painter.drawLine(padding, height - padding, width - padding, height - padding);
    
    // 绘制横坐标标签（星期）
    int dayCount = dates.size();
    int dayWidth = (width - 2 * padding) / (dayCount - 1);
    
    QFont font = painter.font();
    font.setPointSize(8);
    painter.setFont(font);
    
    for (int i = 0; i < dayCount; ++i) {
        int x = padding + i * dayWidth;
        int y = height - padding + 20;
        
        // 绘制星期几
        painter.drawText(x - 15, y, 30, 20, Qt::AlignCenter, dates[i]);
    }
}

void TemperatureChart::drawTemperatureCurve(QPainter &painter)
{
    int width = this->width();
    int height = this->height();
    int padding = 40;
    
    double yMin, yMax;
    calculateYRange(yMin, yMax);
    double yRange = yMax - yMin;
    
    int dayCount = highTemps.size();
    int dayWidth = (width - 2 * padding) / (dayCount - 1);
    
    // 设置曲线画笔
    QPen pen(QColor(138, 43, 226)); // 蓝紫色
    pen.setWidth(3);
    painter.setPen(pen);
    
    // 绘制高温曲线
    QPainterPath path;
    for (int i = 0; i < dayCount; ++i) {
        int x = padding + i * dayWidth;
        int y = height - padding - ((highTemps[i] - yMin) / yRange) * (height - 2 * padding);
        
        if (i == 0) {
            path.moveTo(x, y);
        } else {
            path.lineTo(x, y);
        }
    }
    
    painter.drawPath(path);
}

void TemperatureChart::drawFillArea(QPainter &painter)
{
    int width = this->width();
    int height = this->height();
    int padding = 40;
    
    double yMin, yMax;
    calculateYRange(yMin, yMax);
    double yRange = yMax - yMin;
    
    int dayCount = highTemps.size();
    int dayWidth = (width - 2 * padding) / (dayCount - 1);
    
    // 创建填充路径
    QPainterPath fillPath;
    
    // 移动到第一个点
    int firstX = padding;
    int firstY = height - padding - ((highTemps.first() - yMin) / yRange) * (height - 2 * padding);
    fillPath.moveTo(firstX, firstY);
    
    // 添加曲线上的点
    for (int i = 1; i < dayCount; ++i) {
        int x = padding + i * dayWidth;
        int y = height - padding - ((highTemps[i] - yMin) / yRange) * (height - 2 * padding);
        fillPath.lineTo(x, y);
    }
    
    // 添加右下角点
    fillPath.lineTo(width - padding, height - padding);
    
    // 添加左下角点
    fillPath.lineTo(padding, height - padding);
    
    // 闭合路径
    fillPath.closeSubpath();
    
    // 设置填充画刷
    QBrush brush(QColor(0, 255, 255, 100)); // 青蓝色，半透明
    painter.fillPath(fillPath, brush);
}

void TemperatureChart::drawTemperatureLabels(QPainter &painter)
{
    int width = this->width();
    int height = this->height();
    int padding = 40;
    
    double yMin, yMax;
    calculateYRange(yMin, yMax);
    double yRange = yMax - yMin;
    
    int dayCount = highTemps.size();
    int dayWidth = (width - 2 * padding) / (dayCount - 1);
    
    // 设置标签字体
    QFont font = painter.font();
    font.setPointSize(8);
    font.setBold(true);
    painter.setFont(font);
    
    // 设置标签颜色
    painter.setPen(Qt::black);
    
    for (int i = 0; i < dayCount; ++i) {
        int x = padding + i * dayWidth;
        int y = height - padding - ((highTemps[i] - yMin) / yRange) * (height - 2 * padding);
        
        // 绘制温度值
        QString tempText = QString::number(highTemps[i]) + "°C";
        QRect textRect(x - 15, y - 20, 30, 20);
        painter.drawText(textRect, Qt::AlignCenter, tempText);
        
        // 绘制锚点（加粗）
        painter.setBrush(Qt::black);
        painter.drawEllipse(QPoint(x, y), 4, 4);
    }
}
